<template>
  <el-dialog
    :width="propObj.width?propObj.width:'58%'"
    :title="innerVisible.title"
    :visible.sync="innerVisible.show"
    append-to-body
    custom-class="centerDialog"
    :before-close="handleClose"
    :top="propObj.top?propObj.top:'15vh'">
    <el-row v-if="innerVisible.search">
      <el-col :span="14">
        <el-input v-model="keyword" :placeholder="placeholderMsg" style="width: 96%;" clearable />
      </el-col>
      <el-col :span="10">
        <el-button type="primary" @click="searchData()">搜索</el-button>
      </el-col>
    </el-row>
    <el-row style="margin-top: 15px;">
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="tableData"
        element-loading-text="Loading"
        fit
        key="uiTemplateID"
        highlight-current-row
        @selection-change="changeSelect"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          v-for="(item,index) in propObj.row"
          :key="index"
          :label="item.name"
          :prop="item.code"
        >
          <template slot-scope="scope">
            <div v-if="item.type && item.type === 'img' && scope.row[item.code] && !listLoading">
              <PreviewImg v-if="scope.row[item.code] && !listLoading" :url="scope.row[item.code]" :style-img="50" />
            </div>
            <div v-else>
              <div v-if="scope.row[item.code] && scope.row[item.code].length>12 && !item.type">
                <el-popover
                  placement="top-start"
                  :title="item.name"
                  trigger="hover"
                  width="300"
                >
                  <div>
                    <p>{{ scope.row[item.code] }}</p>
                  </div>
                  <div slot="reference">
                    <span style="cursor: pointer">{{ scope.row[item.code] | returnText }}</span>
                  </div>
                </el-popover>
              </div>
              <span v-else>{{ scope.row[item.code] }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div class="pagination">
          <el-pagination
            v-if="paginations.total > 0"
            :page-size="paginations.page_size"
            :layout="paginations.layout"
            :total="paginations.total"
            :current-page.sync="paginations.page_index"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">关 闭</el-button>
      <el-button :loading="load" type="primary" @click="addList()">添 加</el-button>
    </span>
  </el-dialog>
</template>

<script>
import PreviewImg from '@/components/PreviewImg'
import { returnNewData, returnConstBind } from '@/utils/index'
import {isObject} from "../../utils/validate";
export default {
  components: {
    PreviewImg
  },
  filters: {
    returnTitle(data) {
      return data && data.title ? data.title : ''
    },
    returnText(data) {
      if (data && (data + '').trim()) {
        if (data.length > 0) {
          return data.substring(0, 12) + '...'
        }
      }
      return ''
    }
  },
  props: {
    innerVisible: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      tableData: [],
      keyword: '',
      listLoading: false,
      load: false,
      paginations: {
        page_index: 1,
        page_size: 10,
        total: 0,
        layout: 'total,prev, pager, next '// 翻页属性
      },
      selectContent: [],
      selectList: [],
      placeholderMsg: '请输入关键字',
      propObj: {},
      saveTableSources: [],
      pageParams:{}
    }
  },
  mounted() {
    this.propObj = returnConstBind(this.innerVisible.option)
    if (this.propObj) {
      if (this.innerVisible.bindData && this.innerVisible.bindData.length > 0) {
        this.selectList = [...this.innerVisible.bindData]
      }
      this.getData()
    } else {
      // 数据异常
      this.$message.error('数据异常')
    }
  },
  methods: {
    addList() {
      this.subSelectData()
      if(this.selectList.length === 0){
        this.$message.info("请选择数据")
        return
      }

      if(this.innerVisible.bandFun){
        let ids = this.selectList.map(item=>item.id)
        ids = new Set(ids)
        if(this.innerVisible.one){
          ids = ids[0]
        }
        let mothedType = this.$get
        let url = this.innerVisible.bandFun
        if(isObject(this.innerVisible.bandFun)){
          mothedType = this.innerVisible.bandFun.method
          url = this.innerVisible.bandFun.url
        }
        this.load = true
        mothedType(url,ids).then((res)=>{
          this.load = false
          if (res.data && res.data.code == "OK") {
              this.$message.success('绑定成功')
          }else {
            this.$message.error('绑定失败')
          }
          this.$emit('selectTableData', "reload")
        }).catch(()=>{
          this.load = false
        })
      } else {
        // 去重数据
        const updata = {}
        this.selectList.forEach(item=>{
          updata[item.id] = item
        })
        this.selectList = []
        for (const p in updata){
          this.selectList.push(updata[p])
        }
        if (this.innerVisible.one && this.selectList.length > 1) {
          this.$message({
            message: '只能选择一个，请重新选择！',
            type: 'error'
          })
          this.selectList = []
          this.selectDataTable()
          return
        }
        this.handleClose('reload')
      }
    },
    changeSelect(s) {
      this.selectContent = s
    },
    subSelectData() {
      if (this.selectContent.length > 0) {
        this.selectList = this.selectList.concat(this.selectContent)
      }
    },
    handleClose(msg) {
      if (msg) {
        if (this.innerVisible.sources && this.saveTableSources.length && this.selectList.length) {
          const obj = this.saveTableSources.filter(item => item.id === this.selectList[0].id)
          if (obj.length > 0) {
            this.selectList.push(obj[0])
          }
        }
        this.$emit('selectTableData', this.selectList)
      } else {
        this.$emit('selectTableData', [])
      }
    },
    selectDataTable() {
      /*this.tableData.forEach(attr => {
        attr['id'] = attr[this.innerVisible.attr[0]]
        attr['title'] = attr[this.innerVisible.attr[1]]
        attr['desc'] = attr[this.innerVisible.attr[2]]
      })*/
      this.tableData.forEach(attr => {
        for (const property in this.propObj.attr) {
          attr[property] = attr[this.propObj.attr[property]]
        }
      })
      this.$nextTick(() => {
        this.$refs.multipleTable.clearSelection()
        if (this.selectList.length > 0) {
          this.selectList.forEach(se => {
            this.tableData.forEach((item, index) => {
              if (item.id === se.id) {
                se['dataType'] = 'del'
                this.$refs.multipleTable.toggleRowSelection(this.tableData[index], true)
              }
            })
          })
          this.selectList = this.selectList.filter(item => item['dataType'] !== 'del')
        }
      })
    },
    searchData() {
      this.paginations.page_index = 1
      this.paginations.total = 0
      this.handleCurrentChange(1)
    },
    getData() {
      this.listLoading = true
      const {searchVi,oneVi }  = this.innerVisible
      const {search,one,placeholderMsg }  = this.propObj
      if(searchVi!==undefined){
        this.pageParams.search = searchVi
      } else if(search!== undefined){
        this.pageParams.search = search
      } else {
        this.pageParams.search = false
      }
      this.pageParams.placeholderMsg = placeholderMsg
      if(oneVi !== undefined) {
        this.pageParams.one = oneVi
      } else if(one!== undefined){
        this.pageParams.one = one
      } else {
        this.pageParams.one = true
      }
      this.getTableDataList()
    },
    getTableDataList() {
      let url = '?page=' + this.paginations.page_index + '&rows=' + this.paginations.page_size
      if (this.keyword !== '' && this.propObj.search) {
        let searchName = this.propObj.searchName
        if (!searchName) {
          searchName = 'contentdata'
        }
      }
      this.listLoading = true
      const baseUrl = this.innerVisible.url?this.innerVisible.url:this.propObj.url
      this.$get(baseUrl + url)
        .then((response) => {
          this.listLoading = false;
          if (response.data && response.data.code == "OK") {
            const data = response.data.data;
            this.tableData = data.list;
            this.paginations.total = data.page.total;
            this.selectDataTable()
          }
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    handleCurrentChange(page) {
      this.subSelectData()
      this.paginations.page_index = page
      this.getData()
    }
  }
}
</script>

<style scoped>
  .line{
    text-align: center;
  }
  .input-new-tag {
    width: 180px;
    vertical-align: bottom;
  }
</style>

